package com.loe.logger

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.loe.logger.db.LoggerSharedManager
import com.loe.logger.util.LoggerTools
import org.json.JSONArray
import org.json.JSONObject

class LoggerEnvironmentAdapter(private val context: Context, private var staticList: List<EnvironmentBean>, private val type: String) :
    BaseAdapter()
{
    private var customEnvironmentData: String
        get() = LoggerSharedManager.getString("logger:${type}CustomEnvironmentData")
        set(value)
        {
            LoggerSharedManager.putString("logger:${type}CustomEnvironmentData", value)
        }

    private val customList: ArrayList<EnvironmentBean> by lazy()
    {
        val list = ArrayList<EnvironmentBean>()
        try
        {
            val js = JSONArray(customEnvironmentData)
            for (i in 0 until js.length())
            {
                val json = js.optJSONObject(i)
                val bean = EnvironmentBean(json.optString("type"), json.optString("baseUrl"), true)
                list.add(bean)
            }
        }catch (e: Exception)
        {
        }
        list
    }

    private var onResetListener: (() -> Unit)? = null

    fun setOnResetListener(on: () -> Unit)
    {
        onResetListener = on
    }

    private fun saveCustomEnvironment()
    {
        val js = JSONArray()
        for (bean in customList)
        {
            val json = JSONObject()
            json.put("type", bean.type)
            json.put("baseUrl", bean.baseUrl)
            js.put(json)
        }
        customEnvironmentData = js.toString()
    }

    fun addBean(type: String, baseUrl: String)
    {
        customList.add(EnvironmentBean(type, baseUrl, true))
        notifyDataSetChanged()
        saveCustomEnvironment()
    }

    private val inflater: LayoutInflater = LayoutInflater.from(context)

    override fun getCount(): Int
    {
        return staticList.size + customList.size
    }

    override fun getItem(position: Int): Any
    {
        if (position < staticList.size)
        {
            return staticList[position]
        }
        return customList[position - staticList.size]
    }

    override fun getItemId(position: Int): Long
    {
        return position.toLong()
    }

    override fun getView(position: Int, view: View?, viewGroup: ViewGroup): View
    {
        var view = view
        val bean = getItem(position) as EnvironmentBean

        val item: Item
        if (view == null)
        {
            item = Item()
            // 获取Item布局构造view
            view = inflater.inflate(R.layout.logger_environment_item, null)
            // 获取布局子元素
            item.textType = view!!.findViewById(R.id.textType) as TextView
            item.textUrl = view!!.findViewById(R.id.textUrl) as TextView
            item.buttonDelete = view!!.findViewById(R.id.buttonDelete) as TextView
            // 将Item绑定到view里
            view.tag = item
        } else
        {
            // 如果view已被构造，则直接获取绑定Item
            item = view.tag as Item
        }
        // 显示
        item.textType?.text = bean.type + "："
        val environmentType = if(type == "serve") LoeLogger.environmentServeType else LoeLogger.environmentWebType
        item.textType?.setTextColor(if (environmentType == bean.type) LoggerTools.mainColor else LoggerTools.textColor)
        item.textUrl?.text = bean.baseUrl
        item.buttonDelete?.visibility = if (bean.isCustom) View.VISIBLE else View.GONE
        item.buttonDelete?.setOnClickListener()
        {
            customList.remove(bean)
            val environmentType = if(type == "serve") LoeLogger.environmentServeType else LoeLogger.environmentWebType
            if(environmentType == bean.type)
            {
                onResetListener?.invoke()
            }
            notifyDataSetChanged()
            saveCustomEnvironment()
        }

        return view
    }

    internal inner class Item
    {
        var textType: TextView? = null
        var textUrl: TextView? = null
        var buttonDelete: TextView? = null
    }
}


